import { getProductAuxiliaryUnits, getProductPurchase } from "@/api/product";

import { getProductLatestPrices } from "@/api/purchase/productPrice";

export function calculateAmount(includeTax, exchangeRate, item, quantityField) {
  calculatePrice(includeTax, item);

  if (!item.price) {
    item.amountFr = null;
    item.amount = null;
    item.taxAmountFr = null;
    item.taxAmount = null;
    item.totalAmountFr = null;
    item.totalAmount = null;
  } else {
    item.amountFr = item.priceExcludeTax * item[quantityField];
    item.amount = item.amountFr * exchangeRate;

    item.totalAmountFr = item.priceIncludeTax * item[quantityField];
    item.totalAmount = item.totalAmountFr * exchangeRate;

    item.taxAmountFr = item.totalAmountFr - item.amountFr;

    item.taxAmount = item.totalAmount - item.amount;
  }
}
export function calculatePrice(includeTax, item) {
  if (!item.price) {
    item.priceIncludeTax = null;
    item.priceExcludeTax = null;
  } else {
    let taxRate = item.taxRateValue;

    item.priceIncludeTax = includeTax ? item.price : item.price * (1 + taxRate);
    item.priceExcludeTax = includeTax ? item.price / (1 + taxRate) : item.price;
  }
}

export function calculateBasicQuantity(
  item,
  otherQuantityField,
  basicQuantityField
) {
  basicQuantityField = basicQuantityField
    ? basicQuantityField
    : "basicQuantity";
  if (!item[otherQuantityField] || !item.conversionRate) {
    item[basicQuantityField] = null;
    return;
  }

  item[basicQuantityField] = +item[otherQuantityField] * +item.conversionRate;
}

export function setProductLatestPrice(
  item,
  currencyId,
  supplierId,
  date,
  includeTax
) {
  return new Promise((resolve, reject) => {
    getProductLatestPrices({
      currencyId: currencyId,
      supplierId: supplierId,
      date: date,
      includeTax: includeTax,
      productItems: [
        {
          productId: item.productId,
          basicQuantity: item.basicQuantity,
        },
      ],
    }).then((res) => {
      if (!res || res.length == 0) {
        resolve();
        return;
      }
      let match = res[0];

      item.price = match.price;
      resolve();
    });
  });
}

export function setUnitConversionRate(item, auxiliaryUnitField) {
  return new Promise((resolve, reject) => {
    getProductAuxiliaryUnits({
      productId: item.productId,
      otherUnitId: item[auxiliaryUnitField],
    }).then((res) => {
      if (!res || !res.items || res.items.length == 0) {
        resolve();
        return;
      }
      let match = res.items[0];

      item.conversionRate = match.conversionRate;
      resolve();
    });
  });
}
